@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

:: Minecraft面板Windows自动部署脚本
:: 作者: Minecraft面板开发团队
:: 版本: 1.0.0

title Minecraft面板Windows部署脚本

:: 颜色定义
set "RED=[91m"
set "GREEN=[92m"
set "YELLOW=[93m"
set "BLUE=[94m"
set "NC=[0m"

:: 日志函数
:log_info
echo %BLUE%[INFO]%NC% %~1
goto :eof

:log_success
echo %GREEN%[SUCCESS]%NC% %~1
goto :eof

:log_warning
echo %YELLOW%[WARNING]%NC% %~1
goto :eof

:log_error
echo %RED%[ERROR]%NC% %~1
goto :eof

:: 检查管理员权限
:check_admin
net session >nul 2>&1
if %errorLevel% neq 0 (
    call :log_error "此脚本需要管理员权限运行"
    pause
    exit /b 1
)
call :log_success "管理员权限检查通过"
goto :eof

:: 检查Windows版本
:check_windows
ver | findstr /i "10\.0" > nul
if %errorLevel% equ 0 (
    set "WIN_VERSION=Windows 10/11"
    call :log_info "检测到操作系统: !WIN_VERSION!"
) else (
    ver | findstr /i "6\.3" > nul
    if %errorLevel% equ 0 (
        set "WIN_VERSION=Windows 8.1"
        call :log_info "检测到操作系统: !WIN_VERSION!"
    ) else (
        ver | findstr /i "6\.1" > nul
        if %errorLevel% equ 0 (
            set "WIN_VERSION=Windows 7"
            call :log_info "检测到操作系统: !WIN_VERSION!"
        ) else (
            call :log_warning "未知的Windows版本，继续安装..."
        )
    )
)
goto :eof

:: 安装Chocolatey
:install_chocolatey
call :log_info "安装Chocolatey包管理器..."

:: 检查是否已安装Chocolatey
where choco >nul 2>&1
if %errorLevel% equ 0 (
    call :log_success "Chocolatey已安装"
    goto :eof
)

:: 安装Chocolatey
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "[System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))"

if %errorLevel% neq 0 (
    call :log_error "Chocolatey安装失败"
    pause
    exit /b 1
)

call :log_success "Chocolatey安装完成"
goto :eof

:: 配置Chocolatey国内镜像
:configure_chocolatey_mirror
call :log_info "配置Chocolatey国内镜像..."

choco source remove -n=chocolatey
choco source add -n=chocolatey -s="https://mirrors.tuna.tsinghua.edu.cn/chocolatey/" --priority=1

call :log_success "Chocolatey国内镜像配置完成"
goto :eof

:: 安装基础依赖
:install_dependencies
call :log_info "安装基础依赖包..."

choco install -y git curl wget unzip sqlite nginx

if %errorLevel% neq 0 (
    call :log_error "基础依赖安装失败"
    pause
    exit /b 1
)

call :log_success "基础依赖安装完成"
goto :eof

:: 安装Node.js
:install_nodejs
call :log_info "安装Node.js..."

choco install -y nodejs-lts --version=18.18.0

if %errorLevel% neq 0 (
    call :log_error "Node.js安装失败"
    pause
    exit /b 1
)

:: 设置npm国内镜像
call npm config set registry https://registry.npmmirror.com

:: 验证安装
for /f "tokens=*" %%i in ('node --version') do set NODE_VERSION=%%i
for /f "tokens=*" %%i in ('npm --version') do set NPM_VERSION=%%i

call :log_success "Node.js安装完成: !NODE_VERSION!"
call :log_success "npm安装完成: !NPM_VERSION!"
goto :eof

:: 安装Docker Desktop
:install_docker
call :log_info "安装Docker Desktop..."

:: 检查是否已安装Docker
where docker >nul 2>&1
if %errorLevel% equ 0 (
    call :log_success "Docker已安装"
    goto :eof
)

:: 下载Docker Desktop安装程序
call :log_info "下载Docker Desktop..."
powershell -Command "Invoke-WebRequest -Uri 'https://desktop.docker.com/win/main/amd64/Docker%20Desktop%20Installer.exe' -OutFile '%TEMP%\DockerDesktopInstaller.exe'"

if %errorLevel% neq 0 (
    call :log_error "Docker Desktop下载失败"
    pause
    exit /b 1
)

:: 安装Docker Desktop
call :log_info "安装Docker Desktop..."
%TEMP%\DockerDesktopInstaller.exe install --quiet

if %errorLevel% neq 0 (
    call :log_error "Docker Desktop安装失败"
    pause
    exit /b 1
)

:: 清理安装文件
del %TEMP%\DockerDesktopInstaller.exe

call :log_success "Docker Desktop安装完成"
call :log_warning "请手动启动Docker Desktop并登录"
goto :eof

:: 创建安装目录
:create_directories
call :log_info "创建安装目录..."

set "PANEL_DIR=C:\minecraft-panel"
set "SERVERS_DIR=C:\minecraft-servers"
set "LOG_DIR=C:\minecraft-panel\logs"

:: 创建目录
if not exist "%PANEL_DIR%" mkdir "%PANEL_DIR%"
if not exist "%SERVERS_DIR%" mkdir "%SERVERS_DIR%"
if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"

call :log_success "目录创建完成"
goto :eof

:: 下载并安装Minecraft面板
:install_panel
call :log_info "下载并安装Minecraft面板..."

cd /d "%PANEL_DIR%"

:: 复制面板文件（这里假设代码已经在当前目录）
xcopy /E /I /Y "%~dp0*" "%PANEL_DIR%"

:: 安装依赖
call npm install --production

if %errorLevel% neq 0 (
    call :log_error "依赖安装失败"
    pause
    exit /b 1
)

:: 创建环境配置文件
if not exist ".env" copy ".env.example" ".env"

:: 生成随机密钥
for /f "tokens=*" %%i in ('powershell -Command "[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes((New-Guid).ToString()))"') do set SESSION_SECRET=%%i
powershell -Command "(Get-Content '.env') -replace 'your-secret-key-here-change-this-in-production', '%SESSION_SECRET%' | Set-Content '.env'"

call :log_success "Minecraft面板安装完成"
goto :eof

:: 配置Windows防火墙
:configure_firewall
call :log_info "配置Windows防火墙..."

:: 添加防火墙规则
netsh advfirewall firewall add rule name="MinecraftPanelHTTP" dir=in action=allow protocol=TCP localport=80
netsh advfirewall firewall add rule name="MinecraftPanelHTTPS" dir=in action=allow protocol=TCP localport=443
netsh advfirewall firewall add rule name="MinecraftPanelApp" dir=in action=allow program="%PANEL_DIR%\app.js" enable=yes

call :log_success "Windows防火墙配置完成"
goto :eof

:: 创建Windows服务
:create_windows_service
call :log_info "创建Windows服务..."

:: 检查是否已安装NSSM
where nssm >nul 2>&1
if %errorLevel% neq 0 (
    call :log_info "安装NSSM..."
    choco install -y nssm
)

:: 创建服务
nssm install MinecraftPanel "C:\Program Files\nodejs\node.exe" "%PANEL_DIR%\app.js"
nssm set MinecraftPanel AppDirectory "%PANEL_DIR%"
nssm set MinecraftPanel DisplayName "Minecraft Panel"
nssm set MinecraftPanel Description "Minecraft Server Management Panel"
nssm set MinecraftPanel Start SERVICE_AUTO_START
nssm set MinecraftPanel AppEnvironmentExtra "NODE_ENV=production" "PORT=3000"

:: 配置服务恢复
nssm set MinecraftPanel AppExit Default Restart
nssm set MinecraftPanel AppRestartDelay 10000

call :log_success "Windows服务创建完成"
goto :eof

:: 创建启动脚本
:create_startup_scripts
call :log_info "创建启动脚本..."

:: 创建启动脚本
echo @echo off > "%PANEL_DIR%\start.bat"
echo cd /d "%PANEL_DIR%" >> "%PANEL_DIR%\start.bat"
echo node app.js >> "%PANEL_DIR%\start.bat"
echo pause >> "%PANEL_DIR%\start.bat"

:: 创建停止脚本
echo @echo off > "%PANEL_DIR%\stop.bat"
echo taskkill /F /IM node.exe >> "%PANEL_DIR%\stop.bat"
echo pause >> "%PANEL_DIR%\stop.bat"

:: 创建重启脚本
echo @echo off > "%PANEL_DIR%\restart.bat"
echo call "%PANEL_DIR%\stop.bat" >> "%PANEL_DIR%\restart.bat"
echo timeout /t 2 /nobreak >nul >> "%PANEL_DIR%\restart.bat"
echo call "%PANEL_DIR%\start.bat" >> "%PANEL_DIR%\restart.bat"

call :log_success "启动脚本创建完成"
goto :eof

:: 配置自动备份
:configure_backup
call :log_info "配置自动备份..."

:: 创建备份脚本
echo @echo off > "%PANEL_DIR%\backup.bat"
echo set BACKUP_DIR=%PANEL_DIR%\backups >> "%PANEL_DIR%\backup.bat"
echo if not exist "!BACKUP_DIR!" mkdir "!BACKUP_DIR!" >> "%PANEL_DIR%\backup.bat"
echo for /f "tokens=2 delims==" %%%%i in ('wmic os get localdatetime /value') do set datetime=%%%%i >> "%PANEL_DIR%\backup.bat"
echo set DATE=!datetime:~0,8!_!datetime:~8,6! >> "%PANEL_DIR%\backup.bat"
echo copy "%PANEL_DIR%\database.sqlite" "!BACKUP_DIR!\database_!DATE!.sqlite" >> "%PANEL_DIR%\backup.bat"
echo powershell -Command "Compress-Archive -Path '%PANEL_DIR%\.env' -DestinationPath '!BACKUP_DIR!\config_!DATE!.zip'" >> "%PANEL_DIR%\backup.bat"
echo echo 备份完成: !DATE! >> "%PANEL_DIR%\backup.bat"

:: 创建计划任务
schtasks /create /tn "MinecraftPanelBackup" /tr "%PANEL_DIR%\backup.bat" /sc daily /st 02:00 /ru SYSTEM

call :log_success "自动备份配置完成"
goto :eof

:: 创建桌面快捷方式
:create_shortcuts
call :log_info "创建桌面快捷方式..."

:: 创建桌面快捷方式
set "SHORTCUT=%USERPROFILE%\Desktop\Minecraft Panel.lnk"
powershell -Command "$ws = New-Object -ComObject WScript.Shell; $s = $ws.CreateShortcut('%SHORTCUT%'); $s.TargetPath = '%PANEL_DIR%\start.bat'; $s.WorkingDirectory = '%PANEL_DIR%'; $s.IconLocation = '%PANEL_DIR%\public\images\icon.ico,0'; $s.Save()"

call :log_success "桌面快捷方式创建完成"
goto :eof

:: 显示安装结果
:show_installation_result
call :log_success "Minecraft面板安装完成！"
echo.
echo ==========================================
echo   Minecraft面板安装信息
echo ==========================================
echo 面板访问地址: http://localhost:3000
echo 面板安装目录: %PANEL_DIR%
echo 服务器数据目录: %SERVERS_DIR%
echo 日志目录: %LOG_DIR%
echo.
echo 首次使用请访问: http://localhost:3000/init
echo 完成初始化设置后即可使用面板
echo.
echo 常用命令:
echo   启动面板: net start MinecraftPanel
echo   停止面板: net stop MinecraftPanel
echo   重启面板: net stop MinecraftPanel ^&^& net start MinecraftPanel
echo   查看状态: sc query MinecraftPanel
echo   查看日志: type "%LOG_DIR%\*.log"
echo.
echo 手动启动脚本: %PANEL_DIR%\start.bat
echo 手动停止脚本: %PANEL_DIR%\stop.bat
echo 手动重启脚本: %PANEL_DIR%\restart.bat
echo.
echo ==========================================
goto :eof

:: 主函数
:main
echo ==========================================
echo   Minecraft面板Windows自动部署脚本
echo ==========================================
echo.

:: 检查系统环境
call :check_admin
call :check_windows

:: 安装基础组件
call :install_chocolatey
call :configure_chocolatey_mirror
call :install_dependencies
call :install_nodejs
call :install_docker

:: 配置环境
call :create_directories

:: 安装面板
call :install_panel

:: 配置服务
call :configure_firewall
call :create_windows_service
call :create_startup_scripts
call :configure_backup
call :create_shortcuts

:: 启动服务
net start MinecraftPanel

:: 显示安装结果
call :show_installation_result

call :log_success "所有安装步骤完成！"
pause
goto :eof

:: 运行主函数
call :main